<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>工单处理 - 售后管理系统</title>
  <link rel="stylesheet" href="/after_sale_system/css/common.css">
  <style>
    .filter-bar {
      background-color: white;
      padding: 15px;
      border-radius: 8px;
      margin-bottom: 20px;
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      align-items: center;
    }

    .filter-item {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .filter-item label {
      font-weight: 500;
    }

    .filter-item select, .filter-item input {
      padding: 6px 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    .btn {
      padding: 6px 12px;
      border-radius: 4px;
      border: none;
      cursor: pointer;
    }

    .btn-primary {
      background-color: #667eea;
      color: white;
    }

    .workorder-table {
      width: 100%;
      border-collapse: collapse;
      background-color: white;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .workorder-table th, .workorder-table td {
      padding: 12px 15px;
      text-align: left;
      border-bottom: 1px solid #eee;
    }

    .workorder-table th {
      background-color: #f8f9fa;
      font-weight: 500;
    }

    .action-buttons {
      display: flex;
      gap: 8px;
    }

    .btn-process {
      background-color: #17a2b8;
      color: white;
    }

    .btn-complete {
      background-color: #28a745;
      color: white;
    }

    .priority-high {
      color: #dc3545;
    }

    .priority-medium {
      color: #fd7e14;
    }

    .priority-low {
      color: #28a745;
    }
  </style>
</head>
<body>
<div class="header">
  <h1>售后管理系统 - 客服端</h1>
  <div class="user-info">
    <span>欢迎，<span id="username">客服</span></span>
    <a href="/login" class="logout-btn">退出登录</a>
  </div>
</div>

<div class="container">
  <div class="nav-menu">
    <h2>功能菜单</h2>
    <div class="nav-grid">
      <a href="/after_sale_system/page/customerService/applicationList" class="nav-item">
        <h3>申请审核</h3>
        <p>审核售后申请</p>
      </a>
      <a href="/after_sale_system/page/customerService/workOrder" class="nav-item">
        <h3>工单处理</h3>
        <p>处理售后工单</p>
      </a>
    </div>
  </div>

  <div class="content">
    <h2>售后工单处理</h2>

    <div class="filter-bar">
      <div class="filter-item">
        <label for="statusFilter">工单状态:</label>
        <select id="statusFilter">
          <option value="">全部状态</option>
          <option value="PROCESSING">处理中</option>
          <option value="PENDING">待处理</option>
          <option value="COMPLETED">已完成</option>
        </select>
      </div>
      <div class="filter-item">
        <label for="priorityFilter">优先级:</label>
        <select id="priorityFilter">
          <option value="">全部优先级</option>
          <option value="HIGH">高</option>
          <option value="MEDIUM">中</option>
          <option value="LOW">低</option>
        </select>
      </div>
      <div class="filter-item">
        <label for="searchKeyword">搜索:</label>
        <input type="text" id="searchKeyword" placeholder="工单ID/商品名">
      </div>
      <div class="filter-item">
        <button class="btn btn-primary" id="searchBtn">查询</button>
        <button class="btn" id="resetBtn">重置</button>
      </div>
    </div>

    <table class="workorder-table">
      <thead>
      <tr>
        <th>工单ID</th>
        <th>关联申请</th>
        <th>商品名称</th>
        <th>类型</th>
        <th>优先级</th>
        <th>状态</th>
        <th>创建时间</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody id="workordersTableBody">
      <tr><td colspan="8" class="loading"><div class="spinner"></div> 加载中...</td></tr>
      </tbody>
    </table>

    <div class="pagination" id="pagination">
      <!-- 分页控件将通过JavaScript动态生成 -->
    </div>
  </div>
</div>

<!-- 处理工单弹窗 -->
<div class="modal" id="processModal">
  <div class="modal-content">
    <div class="modal-header">
      <h3>处理工单</h3>
      <span class="close-btn">&times;</span>
    </div>
    <div class="modal-body">
      <input type="hidden" id="workorderId">
      <div class="form-group">
        <label for="processRemark">处理记录:</label>
        <textarea id="processRemark" rows="4" class="form-control" required></textarea>
      </div>
      <div class="form-group">
        <label for="processStatus">处理状态:</label>
        <select id="processStatus" class="form-control">
          <option value="PROCESSING">处理中</option>
          <option value="COMPLETED">已完成</option>
        </select>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-primary" id="saveProcessBtn">保存</button>
    </div>
  </div>
</div>

<script src="/after_sale_system/js/common.js"></script>
<script>
  let currentPage = 1;
  const pageSize = 10;

  document.addEventListener('DOMContentLoaded', function() {
    loadWorkOrders();

    // 搜索按钮事件
    document.getElementById('searchBtn').addEventListener('click', function() {
      currentPage = 1;
      loadWorkOrders();
    });

    // 重置按钮事件
    document.getElementById('resetBtn').addEventListener('click', function() {
      document.getElementById('statusFilter').value = '';
      document.getElementById('priorityFilter').value = '';
      document.getElementById('searchKeyword').value = '';
      currentPage = 1;
      loadWorkOrders();
    });

    // 关闭弹窗
    document.querySelector('.close-btn').addEventListener('click', function() {
      document.getElementById('processModal').style.display = 'none';
    });

    // 保存处理结果按钮
    document.getElementById('saveProcessBtn').addEventListener('click', saveProcessResult);
  });

  // 加载工单列表
  function loadWorkOrders() {
    const status = document.getElementById('statusFilter').value;
    const priority = document.getElementById('priorityFilter').value;
    const keyword = document.getElementById('searchKeyword').value;

    let url = `/after_sale_system/api/workorder`;
    const params = new URLSearchParams();
    if (status) params.append('status', status);
    if (priority) params.append('priority', priority);
    if (keyword) params.append('keyword', keyword);

    if (params.toString()) url += `?${params.toString()}`;

    fetch(url)
            .then(response => response.json())
            .then(data => {
              if (data.success) {
                renderWorkOrdersTable(data.data);
              } else {
                showMessage(data.message, 'error');
              }
            })
            .catch(error => {
              showMessage('加载失败，请重试', 'error');
              console.error(error);
            });
  }

  // 渲染工单表格
  function renderWorkOrdersTable(workorders) {
    const tableBody = document.getElementById('workordersTableBody');
    tableBody.innerHTML = '';

    if (workorders.length === 0) {
      tableBody.innerHTML = '<tr><td colspan="8" style="text-align:center">暂无工单</td></tr>';
      return;
    }

    workorders.forEach(order => {
      const row = document.createElement('tr');
      row.innerHTML = `
                    <td>${order.id}</td>
                    <td><a href="/after_sale_system/page/customerService/applicationDetail?id=${order.applicationId}">申请#${order.applicationId}</a></td>
                    <td>${order.productName}</td>
                    <td>${formatAfterSaleType(order.type)}</td>
                    <td><span class="priority-${order.priority.toLowerCase()}">${order.priority}</span></td>
                    <td>${formatStatus(order.status)}</td>
                    <td>${formatDateTime(order.createTime)}</td>
                    <td class="action-buttons">
                        <button class="btn btn-sm btn-process" onclick="showProcessModal(${order.id})">处理</button>
                    </td>
                `;
      tableBody.appendChild(row);
    });
  }

  // 显示处理弹窗
  function showProcessModal(workorderId) {
    document.getElementById('workorderId').value = workorderId;
    document.getElementById('processRemark').value = '';
    document.getElementById('processStatus').value = 'PROCESSING';
    document.getElementById('processModal').style.display = 'block';
  }

  // 保存处理结果
  function saveProcessResult() {
    const workorderId = document.getElementById('workorderId').value;
    const remark = document.getElementById('processRemark').value;
    const status = document.getElementById('processStatus').value;

    if (!remark.trim()) {
      showMessage('请输入处理记录', 'warning');
      return;
    }

    fetch(`/after_sale_system/api/workorder/process/${workorderId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `status=${status}&remark=${encodeURIComponent(remark)}`
    })
            .then(response => response.json())
            .then(data => {
              if (data.success) {
                showMessage('处理成功', 'success');
                document.getElementById('processModal').style.display = 'none';
                loadWorkOrders(); // 重新加载列表
              } else {
                showMessage(data.message, 'error');
              }
            })
            .catch(error => {
              showMessage('处理失败，请重试', 'error');
              console.error(error);
            });
  }
</script>
</body>
</html>